package com.leetao.netty.core;

import com.leetao.netty.config.NettyConfig;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * NettyServerInitializer
 * @author 菅江晖
 * @date 2021/4/15 - 16:08
 */
@Component
public class WebSocketServerInitializer extends ChannelInitializer<Channel> {

    @Autowired
    NettyConfig nettyConfig;
    @Autowired
    WebSocketServerHandler nettyServerHandler;


    @Override
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        // 处理日志
        pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));

        // 处理心跳 60S客户端没有信息，则断开该链接（客户端每10s进行一次心跳检测，25S可认为该客户端处于异常状态，服务端可以进行下线处理）
        pipeline.addLast(new IdleStateHandler(60, 0, 0));
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(nettyConfig.getMaxContentLength()));
        pipeline.addLast(nettyServerHandler);
        pipeline.addLast(new WebSocketServerProtocolHandler(nettyConfig.getWsPath(), null, true, 65535));

    }
}
